import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

// 获取所有新闻（包括未发布的）
export async function GET() {
  try {
    const news = await db.all<any>(`
      SELECT 
        id, title, summary, content, image, images, category, tags, author,
        publish_date as publishDate, is_published as isPublished, 
        is_pinned as isPinned, view_count as viewCount,
        created_at as createdAt, updated_at as updatedAt
      FROM news 
      ORDER BY is_pinned DESC, created_at DESC
    `);
    
    // 解析images字段（JSON字符串转数组）
    const processedNews = news.map(item => ({
      ...item,
      images: item.images ? JSON.parse(item.images) : []
    }));
    
    return NextResponse.json({
      success: true,
      data: processedNews
    });
  } catch (error) {
    console.error('Error fetching all news:', error);
    return NextResponse.json({
      success: false,
      error: 'Failed to fetch news'
    }, { status: 500 });
  }
}

// 创建新闻
export async function POST(request: NextRequest) {
  try {
    const data = await request.json();
    const id = Date.now().toString();
    const now = new Date().toISOString();
    
    await db.run(`
      INSERT INTO news (
        id, title, summary, content, image, images, category, 
        author, publish_date, is_published, is_pinned, 
        view_count, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `, [
      id, data.title, data.summary || '', data.content, 
      data.image || null, JSON.stringify(data.images || []), data.category || 'news',
      data.author || 'admin', data.publishDate || now,
      data.isPublished ? 1 : 0, data.isPinned ? 1 : 0,
      0, now, now
    ]);
    
    return NextResponse.json({
      success: true,
      data: { id, ...data }
    });
  } catch (error) {
    console.error('Error creating news:', error);
    return NextResponse.json({
      success: false,
      error: 'Failed to create news'
    }, { status: 500 });
  }
}